<template>
  <el-card class="content">
    <el-row>
      <el-col :span="4">
        <span>角色名：</span>
        <el-input
          placeholder="请输入角色名"
          size="mini"
          style="width: 200px"
          v-model="query.roleName"
          clearable
        >
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-button class="black-button" @click="getRoleList" size="small"
          >查询</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="addDialogVisible = true"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <p class="bg-purple">角色信息列表</p>
    <el-table stripe size="small" :data="roleList">
      <el-table-column
        prop="roleName"
        label="角色名"
        align="center"
      ></el-table-column>
      <el-table-column prop="description" label="角色描述" align="center">
      </el-table-column>
      <el-table-column prop="tailingPondName" label="尾矿库" align="center">
      </el-table-column>
      <el-table-column prop="unitName" label="企业" align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
      ></el-table-column>
      <el-table-column prop="address" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="updateRoleInfo(scope.row)"
            >修改</el-button
          >
          <el-button type="text" size="small" @click="delRole(scope.row.id)"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="getRoleAuthorizations(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" justify="end">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 15]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <!-- 新增角色信息 -->
    <el-dialog
      title="添加角色信息"
      :visible.sync="addDialogVisible"
      width="25%"
      @close="closeDialogVisible"
    >
      <el-form
        :model="addListForm"
        ref="addListForm"
        label-width="120px"
        :rules="rules"
        label-position="left"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input
            v-model="addListForm.roleName"
            placeholder="请填写角色名"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="addListForm.description"
            placeholder="请填写角色描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="尾矿库" prop="tailingPondId">
          <el-select
            v-model="addListForm.tailingPondId"
            style="display: flex"
            placeholder="请选择尾矿库"
          >
            <el-option
              v-for="item in tailingList"
              :key="item.id"
              :label="item.tailingName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="buttonfrom">
          <el-button type="primary" @click="addRoleList">确 定</el-button>
          <el-button @click="closeDialogVisible">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改角色信息 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editDialogVisible"
      width="30%"
    >
      <el-form
        :model="editListForm"
        ref="editListForm"
        label-width="120px"
        :rules="rules"
        label-position="left"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input
            v-model="editListForm.roleName"
            placeholder="请填写角色名"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="editListForm.description"
            placeholder="请填写角色描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="尾矿库" prop="tailingPondId">
          <el-select
            v-model="editListForm.tailingPondId"
            style="display: flex"
            placeholder="请选择尾矿库"
          >
            <el-option
              v-for="item in tailingList"
              :key="item.id"
              :label="item.tailingName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="buttonfrom">
          <el-button type="primary" @click="isEditRoleInfo">确 定</el-button>
          <el-button @click="editDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配角色权限 -->
    <el-dialog
      title="分配角色权限"
      :visible.sync="authDialogVisible"
      width="30%"
    >
      <el-tree
        :data="roleAuthorizationsList"
        ref="treeRef"
        show-checkbox
        node-key="id"
        check-strictly
        :render-after-expand="false"
        default-expand-all
        :props="treeProps"
        :default-checked-keys="roleAuthorization"
        style="display: block; height: 600px; overflow-y: auto"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer" style="margin-right: 200px">
        <el-button type="primary" @click="addRoleAuthorizations"
          >确 定</el-button
        >
        <el-button @click="authDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getRoleByPage,
  getTailingPondList,
  getRoleAuthorizations,
  bindRoleAuthorization,
} from "../../../api/system-management-api";
import axios from "axios";
export default {
  name: "RoleManagementChild",
  data() {
    return {
      query: {
        page: 1,
        pagesize: 10,
        roleName: "",
        roleId: null,
        authorizationIds: [],
      },
      total: null,
      roleList: [],
      addDialogVisible: false,
      addListForm: {
        roleName: "",
        description: "",
        tailingPondId: null,
        unitId: sessionStorage.getItem("unitId"),
      },
      editDialogVisible: false,
      editListForm: {
        id: null,
        roleName: "",
        description: "",
        tailingPondId: null,
        platformId: sessionStorage.getItem("platformId"),
        unitId: sessionStorage.getItem("unitId"),
      },
      roleTypeList: [
        { id: 0, name: "管理员" },
        { id: 1, name: "集团端" },
        { id: 2, name: "企业端" },
      ],
      // 尾矿库列表选择
      tailingList: [],
      dialogWidth: null,
      // 添加角色表单验证
      rules: {
        roleName: [
          { required: true, message: "请输入角色姓名", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
        tailingPondId: [
          { required: true, message: "请选择尾矿库", trigger: "change" },
        ],
        unitId: [{ required: true, message: "请选择企业", trigger: "change" }],
      },
      // 分配权限对话框是否隐藏
      authDialogVisible: false,
      //  当前分配的角色id
      roleId: "",
      // 所有权限数据
      roleAuthorizationsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: "name",
        children: "children",
      },
      // 默认选中的节点id值数组
      roleAuthorization: [],
      // 分配角色已有权限
      authorizationIds: [],
    };
  },
  created() {
    this.getRoleList();
    this.getTailingList();
  },
  methods: {
    // 分页查询角色列表
    async getRoleList() {
      const res = await getRoleByPage({
        pageCount: this.query.page,
        pageSize: this.query.pagesize,
        unitId: sessionStorage.getItem("unitId"),
        roleName: this.query.roleName,
      });
      if (res.resultCode == "204") {
        this.$message({
          message: "暂无数据",
          offset: 400,
          duration: 1000,
        });
        this.roleList = [];
      }
      if (res.resultCode == "400") {
        this.$message({
          type: "error",
          message: "查询失败",
          offset: 400,
          duration: 1000,
        });
        this.roleList = [];
      }
      console.log(res);
      this.roleList = res.parameter.list;
      this.total = res.parameter.total;
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(val) {
      this.query.pagesize = val;
      this.getRoleList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(val) {
      this.query.page = val;
      this.getRoleList();
    },
    //尾矿库列表类型
    async getTailingList() {
      const res = await getTailingPondList({
        unitId: sessionStorage.getItem("unitId"),
      });
      console.log(res);
      this.tailingList = res.parameter;
    },
    // 添加确定
    addRoleList() {
      this.$refs.addListForm.validate(async (val) => {
        if (val) {
          const formData = new FormData();
          for (const [key, value] of Object.entries(this.addListForm)) {
            formData.append(key, value);
          }
          axios({
            method: "post",
            url: "/role/addUnitRole",
            data: formData,
          }).then((res) => {
            if (res.data.resultCode == "200") {
              this.getRoleList();
              this.$message({
                type: "success",
                message: "新增成功",
                offset: 400,
                duration: 1000,
              });
              this.$refs.addListForm.resetFields();
            } else if (res.data.resultCode == "400") {
              this.$message({
                type: "error",
                message: "新增失败",
                offset: 400,
                duration: 1000,
              });
            }
          });
          this.addDialogVisible = false;
        } else {
          this.$message({
            type: "error",
            message: "请完善表单信息",
            offset: 400,
            duration: 1000,
          });
        }
      });
      this.$refs.addListForm.resetFields();
    },
    //添加取消
    closeDialogVisible() {
      this.addDialogVisible = false;
      this.$refs.addListForm.resetFields();
    },
    // 将原数据回显
    updateRoleInfo(row) {
      console.log(row);
      this.editListForm.id = row.id;
      this.editListForm.roleName = row.roleName;
      this.editListForm.platformId = row.platformId;
      this.editListForm.description = row.description;
      this.editListForm.tailingPondId = row.tailingPondId;
      this.editListForm.unitId = row.unitId;
      this.editDialogVisible = true;
    },
    // 确定修改角色信息
    isEditRoleInfo() {
      this.$refs.editListForm.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          for (const [key, value] of Object.entries(this.editListForm)) {
            formData.append(key, value);
          }
          axios({
            method: "post",
            url: "/role/updateRole",
            data: formData,
          }).then((res) => {
            if (res.data.resultCode == 200) {
              this.getRoleList();
              this.$message({
                type: "success",
                message: "修改成功",
                offset: 400,
                duration: 1000,
              });
            } else if (res.data.resultCode == "400") {
              this.$message({
                type: "error",
                message: "修改失败",
                offset: 400,
                duration: 1000,
              });
            }
            this.editDialogVisible = false;
          });
        } else {
          this.$message({
            type: "error",
            message: "请完成表单",
            offset: 400,
            duration: 1000,
          });
        }
      });
    },
    // 删除角色信息
    delRole(id) {
      this.$confirm("确定删除吗？")
        .then((_) => {
          axios({
            method: "get",
            url: "/role/deleteRole/" + `${id}`,
          }).then((res) => {
            if (res.data.resultCode == "200") {
              this.getRoleList();
              this.$message({
                type: "success",
                message: "删除成功",
                offset: 400,
                duration: 1000,
              });
            } else if (res.data.resultCode == "400") {
              this.$message({
                type: "error",
                message: "删除失败",
                offset: 400,
                duration: 1000,
              });
            }
          });
        })
        .catch((_) => {
          this.$message({
            type: "info",
            message: "已取消删除",
            offset: 400,
            duration: 1000,
          });
        });
    },
    //分配权限的数据
    async getRoleAuthorizations(row) {
      this.roleId = row.id;
      const res = await getRoleAuthorizations({
        roleId: row.id,
      });
      if (res.resultCode == "200") {
        console.log(res);
        this.roleAuthorizationsList = res.parameter.authorizationDtoList;
        this.roleAuthorization = res.parameter.roleAuthorization;
        // 递归获取三级节点的id
        this.getLeafKeys(row, this.roleAuthorization);
        this.authDialogVisible = true;
      } else {
        this.$message({
          message: "暂无分配权限数据",
          offset: 400,
          duration: 1000,
        });
        this.authDialogVisible = false;
      }
    },
    // 通过递归获取角色三级权限id 并保存到roleAuthorization数组中
    getLeafKeys(node, arr) {
      // 判断是否为三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      for (let i = 0; i < node.children.length; i++) {
        this.getLeafKeys(node.children[i], arr);
      }
    },

    // 点击为角色分配权限
    async addRoleAuthorizations() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      console.log(keys);
      await bindRoleAuthorization({
        roleId: this.roleId,
        authorizationIds: keys.join(","),
      }).then((res) => {
        console.log(res);
        if (res.resultCode == "200") {
          this.$message({
            type: "success",
            message: "分配权限成功",
            offset: 400,
            duration: 1000,
          });
        } else {
          this.$message({
            type: "error",
            message: "分配权限失败",
            offset: 400,
            duration: 1000,
          });
        }
      });
      this.authDialogVisible = false;
    },
    setDialogWidth() {
      var val = document.body.clientWidth;
      const def = 750; // 默认宽度
      if (val < def) {
        this.dialogWidth = "100%";
      } else {
        this.dialogWidth = def + "px";
      }
    },
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.setDialogWidth();
      })();
    };
  },
};
</script>

<style scoped>
.content {
  height: 87vh;
}

.black-button {
  background-color: black;
  color: white;
}

.bg-purple {
  background: #d3dce6;
  height: 30px;
  font-size: 14px;
  line-height: 30px;
  padding-left: 10px;
}
.el-button {
  font-size: 14px;
}
.el-table {
  display: block;
  height: 67.2vh;
  overflow-y: auto;
  margin-bottom: 15px;
}
.el-table::before {
  z-index: inherit;
}
</style>
